<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <!-- <el-breadcrumb-item><a href="/users">用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUesrList"
          >
            <!-- 就 是 点 击 清 空 触 发 事 件   -->
            <el-button slot="append" icon="el-icon-search" @click="getUesrList"></el-button>
            <!-- 搜 索 的 按 钮 触 发 点 击 事 件  -->
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width:100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- switch区域 -->
          <template slot-scope="scope">
            <!-- {{scope.row}}   作用域插槽  可以根据scope.row 获取到当前这一行的数据   -->
            <el-switch v-model="scope.row.mg_state" @change="changeSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!--三个按钮  ，可修改，可删除 分配角色 -->
        <el-table-column label="操作" width="180px">
          <!--  这个是自己定义的  也是使用作用域插槽 -->
          <template slot-scope="scopes">
            <!-- <el-button type="primary" icon="el-icon-edit" size="mini" @click="editButton(scopes.row.id)"></el-button>  还有另外一种写法-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editButton(scopes.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scopes.row.id)"
            ></el-button>
            <!-- tooltip  经过的时候显示内容 文字提示  -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!-- enterable属性就是鼠标离开的时候 文字消失 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="openSetting(scopes.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totol"
      ></el-pagination>
    </el-card>
    <!-- ////添加用户提示框 -->
    <!-- close方法就是这个关闭弹框的时候触发 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUSer">确 定</el-button>
      </span>
    </el-dialog>

    <!-- ////编辑弹出的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editdialogVisible" width="50%" @close="editDialogClose">
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="settingdialogVisible" @close="closeSetting" width="50%">
      <div>
        <p>用户名 :  {{usersInfo.username}}</p>
        <p>用户角色 :  {{usersInfo.role_name}}</p>
        <p>分配新角色<el-select clearable v-model="selectedRoleid" placeholder="请选择">
    <el-option
      v-for="item in settings"
      :key="item.id"
      :label="item.roleName"
      :value="item.id" 
      
      >
    </el-option>
  </el-select></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="settingupdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  //1.获取数据
  data() {
    ////就是自定义验证规则  定义后面跟一个函数
    var changeEmail = (rule, value, callback) => {
      //验证邮箱的正则表达式
      var regmail = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
      if (regmail.test(value)) {
        return callback();
      }
      // 如果不合法 就传一个回调函数  固定的写法
      callback(new Error("请输入正确的邮箱"));
    };
    var changeMobile = (rule, value, callback) => {
      //验证邮箱的正则表达式
      var regMoile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (regMoile.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的手机号码"));
    };
    return {
      userList: [],
      queryInfo: {
        //////查询参数
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      totol: 0,
      ///添加的
      dialogVisible: false,
      //编辑的
      editdialogVisible: false,
      settingdialogVisible: false,
      usersInfo: "",
      ///添加
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //编辑
      editForm: {
        id: "",
        username: "",
        email: "",
        mobile: ""
      },
      // 获取到角色列表的所有信息
      settings:[],
      selectedRoleid:'',      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" }
        ],
        // 验证规则 必须要这个vaildator 来进行验证
        email: [{ validator: changeEmail, trigger: "blur" }],
        mobile: [{ validator: changeMobile, trigger: "blur" }]
      }
    };
  },
  methods: {
    async getUesrList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error("失败");
      this.userList = res.data.users;
      this.totol = res.data.total;
      //   console.log(this.userList);
    },
    //   定义的时候是自定义事件，所以我们都要用参数来接受
    handleSizeChange(newSize) {
      // console.log(newSize);
      /////切换一个显示多少条数据 ，那么 我对应的页面就是要显示多少条
      this.queryInfo.pagesize = newSize;
      this.getUesrList();
    },
    handleCurrentChange(newNum) {
      /////页码值发生变化的时候会触发 下面显示的
      // console.log(newNum);
      this.queryInfo.pagenum = newNum;
      this.getUesrList();
    },
    async changeSwitch(usersInfo) {
      // console.log(usersInfo);
      let { data: res } = await this.$http.put(
        `users/${usersInfo.id}/state/${usersInfo.mg_state}`
      );
      // console.log(res);

      if (res.meta.status !== 200) {
        /////如果诶呦修改成功 ，就让他马上跳回来
        usersInfo.mg_state = !usersInfo.mg_state;
        this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
    },

    // <!-- close方法就是这个关闭弹框的时候触发 -->
    addDialogClose() {
      this.$refs.ruleForm.resetFields();
    },

    addUSer() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.ruleForm);

        if (res.meta.status != 201) this.$message.error("新增失败");

        this.$message.success("新增成功");
        this.getUesrList();
        this.dialogVisible = false;
      });
    },

    // 修改按钮
    //  async editButton(id) {
    //    this.editForm.id=id;
    //     this.editdialogVisible = true;
    //    const {data:res} =  await this.$http.get("users/" + id,this.editForm);
    //     if(res.meta.status!==200) return
    //     console.log(res);
    //     this.editForm=res.data;
    //   },

    //////// 修改按钮的另外一种写法
    editButton(usersInfos) {
      console.log(usersInfos);
      this.editdialogVisible = true;
      this.editForm.id = usersInfos.id;
      this.editForm.username = usersInfos.username;
      this.editForm.mobile = usersInfos.mobile;
      this.editForm.email = usersInfos.email;
    },
    ////修改数据里面的表单重置
    editDialogClose() {
      this.$refs.editForm.resetFields();
    },
    ///这个是编辑数据里面的确定按钮
    editUser() {
      this.$refs.editForm.validate(async valid => {
        //  console.log(this.editForm.id);
        if (!valid) return;
        ///发送请求 并且返回数据
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        );
        if (res.meta.status != 200) this.$message.error("修改失败");
        this.$message.success("修改成功");
        this.getUesrList();
        this.editdialogVisible = false;
      });
    },
    // 删除按钮
    async delUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showCancelButton: true,
          type: "warning"
        }
      ).catch(err => err);
      console.log(confirmResult);
      if (confirmResult != "confirm") return this.$message.info("没有进行删除");
      const { data: res } = await this.$http.delete("users/" + id);
      console.log(res);
      if (res.meta.status == 400)
        return this.$message.info("系统用户，不可以删除");
      if (res.meta.status !== 200) return;
      this.$message.success("删除成功");
      this.getUesrList();
    },
    async openSetting(userInfo) {
      this.usersInfo = userInfo;
      //   在打开弹窗之前获取到角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("出巡失败");
      this.settings = res.data;
      console.log(this.settings);
      this.settingdialogVisible = true;
    },
    // 修改角色
   async settingupdate(){
     const {data:res} =await this.$http.put(`users/${this.usersInfo.id}/role`,{
     rid:this.selectedRoleid
     })
    //  console.log(res);
    if(res.meta.status!==200) return this.$message.error("修改失败")
  this.$message.success("修改成功")
   this.settingdialogVisible = false;
   this.getUesrList();
     
    }
    ,closeSetting(){
    
        this.selectedRoleid=''
        this.usersInfo=''
      
    }
  },
  created() {
    this.getUesrList();
  }
};
</script>
<style lang="less" scoped>
</style>